package com.tianyu.service.base;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.tianyu.model.dto.AircraftLedgerInfoDTO;
import com.tianyu.model.dto.CurrentProcessCommand;
import com.tianyu.model.dto.DockLedgerInfoDTO;
import com.tianyu.model.dto.FlyToPointDTO;
import com.tianyu.model.entity.Device;
import com.tianyu.model.enums.DockTypeEnum;
import com.tianyu.model.enums.ThirdMethodEnum;
import com.tianyu.model.ro.ServiceRo;
import com.tianyu.service.base.api.CommandReceive;
import com.tianyu.service.cache.DataCacheService;
import com.tianyu.service.http.HttpRequest;
import com.tianyu.service.mqtt.handler.outbound.CommandSendService;
import com.tianyu.service.mqtt.model.def.TianyuPB;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;

/**********************************
 * @Author YSW
 * @Description
 * @Date 2024/7/16 - 17:07
 **********************************/

@Slf4j
@Service
public class IThird01CommandReceive implements CommandReceive {

    @Resource
    private DataCacheService dataCacheService;

    @Resource
    private CommandSendService commandSendService;

    @Resource
    private DeviceService deviceService;

    @Resource
    private HttpRequest httpRequest;

    /**
     * 获取机场遥测信息
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> dockLedgerInfo(JSONObject params) {
        // 设备编号（飞行器/机库）不填默认查询全部
        final String sn = params.getString("sn");
        final String companyCode = params.getString("companyCode");

        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode);
        final JSONObject hangarListGet = httpRequest.hangarListGet(DataCacheService.tianyuLoginMap.get(ykCompanyId));
        System.out.println(hangarListGet);
        final JSONArray content = hangarListGet.getJSONArray("content");
        final JSONArray objects = JSONArray.of();
        if (sn != null) {
            final Optional<Object> objectOptional = content.stream().filter(o -> Objects.equals(JSONObject.from(o).getString("hangarId"), sn)).findFirst();
            if (objectOptional.isPresent()) {
                final JSONObject dockOsd = JSONObject.from(objectOptional.get());
                final DockTypeEnum hangarType = DockTypeEnum.findByCode(dockOsd.getInteger("hangarType"));
                objects.add(DockLedgerInfoDTO.builder()
                        .sn(sn)
                        .name(dockOsd.getString("hangarName"))
                        .brand(hangarType.getName())
                        .brandCnName(hangarType.getDesc())
                        .model("")
                        .longitude(dockOsd.getDouble("hangarLng"))
                        .latitude(dockOsd.getDouble("hangarLat"))
                        .build());
            } else {
                return ServiceRo.resultFailed("设备信息获取错误, 设备不在该公司下");
            }
        } else {
            for (Object device : content) {
                final JSONObject dockOsd = JSONObject.from(device);
                final DockTypeEnum hangarType = DockTypeEnum.findByCode(dockOsd.getInteger("hangarType"));
                objects.add(DockLedgerInfoDTO.builder()
                        .sn(dockOsd.getString("hangarId"))
                        .name(dockOsd.getString("hangarName"))
                        .brand(hangarType.getName())
                        .brandCnName(hangarType.getDesc())
                        .model("")

                        .longitude(dockOsd.getDouble("hangarLng"))
                        .latitude(dockOsd.getDouble("hangarLat"))
                        .build());
            }
        }
        return ServiceRo.resultSuccess(JSONObject.of("rows", objects));
    }

    /**
     * 获取飞行器遥测信息
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> aircraftLedgerInfo(JSONObject params) {
        // 设备编号（飞行器/机库）不填默认查询全部
        final String sn = params.getString("sn");
        final String companyCode = params.getString("companyCode");
        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode);
        final JSONObject hangarListGet = httpRequest.hangarListGet(DataCacheService.tianyuLoginMap.get(ykCompanyId));
        final JSONArray hangarList = hangarListGet.getJSONArray("content");
        final JSONObject jsonObject = httpRequest.boxListGet(DataCacheService.tianyuLoginMap.get(ykCompanyId));
        final JSONArray content = jsonObject.getJSONArray("content");
        log.info(content.toJSONString());
        final JSONArray objects = JSONArray.of();
        if (sn != null) {
            final Optional<Object> optional = content.stream().filter(o -> {
                final JSONObject box = JSONObject.from(o);
                return sn.equals(box.getString("boxSn"));
            }).findFirst();
            if (optional.isPresent()) {
                final JSONObject box = JSONObject.from(optional.get());
                final Optional<Object> objectStream = hangarList.stream().filter(o -> {
                    final JSONObject box0 = JSONObject.from(o);
                    return sn.equals(box0.getString("boxSn"));
                }).findFirst();
                if (objectStream.isPresent()) {
                    final JSONObject object = JSONObject.from(objectStream.get());
                    final String hangarId = object.getString("hangarId");
                    final Double hangarLng = object.getDouble("hangarLng");
                    final Double hangarLat = object.getDouble("hangarLat");
                    objects.add(AircraftLedgerInfoDTO.builder()
                            .sn(sn)
                            .name(box.getString("boxName"))
                            .type("2")
                            .category("3")
                            .picture("")
                            .longitude(hangarLng)
                            .latitude(hangarLat)
                            .brand("DJI")
                            .brandCnName("大疆")
                            .model("M30")
                            .modelCnName("大疆机场M30")
                            .dockSn(hangarId)
                            .modifyTime(box.getString("startTime"))
                            .build());
                } else {
                    objects.add(AircraftLedgerInfoDTO.builder()
                            .sn(sn)
                            .name(box.getString("boxName"))
                            .type("2")
                            .category("3")
                            .picture("")
                            .longitude(0.0)
                            .latitude(0.0)
                            .brand("DJI")
                            .brandCnName("大疆")
                            .model("M30")
                            .modelCnName("大疆机场M30")
                            .dockSn("")
                            .modifyTime(box.getString("startTime"))
                            .build());
                }
            } else {
                return ServiceRo.resultFailed("设备信息获取错误, 设备不在该公司下");
            }
        } else {
            for (Object device : content) {
                final JSONObject box = JSONObject.from(device);
                final String boxSn = box.getString("boxSn");
                final String startTime = box.getString("startTime");
                final Optional<Object> objectStream = hangarList.stream().filter(o -> {
                    final JSONObject box0 = JSONObject.from(o);
                    return boxSn.equals(box0.getString("boxSn"));
                }).findFirst();
                if (objectStream.isPresent()) {
                    final JSONObject object = JSONObject.from(objectStream.get());
                    final String hangarId = object.getString("hangarId");
                    final Double hangarLng = object.getDouble("hangarLng");
                    final Double hangarLat = object.getDouble("hangarLat");
                    objects.add(AircraftLedgerInfoDTO.builder()
                            .sn(boxSn)
                            .name(box.getString("boxName"))
                            .type("2")
                            .category("3")
                            .picture("")
                            .longitude(hangarLng)
                            .latitude(hangarLat)
                            .brand("DJI")
                            .brandCnName("大疆")
                            .model("M30")
                            .modelCnName("大疆机场M30")
                            .dockSn(hangarId)
                            .modifyTime(startTime)
                            .build());
                } else {
                    objects.add(AircraftLedgerInfoDTO.builder()
                            .sn(boxSn)
                            .name(box.getString("boxName"))
                            .type("2")
                            .category("3")
                            .picture("")
                            .longitude(0.0)
                            .latitude(0.0)
                            .brand("DJI")
                            .brandCnName("大疆")
                            .model("M30")
                            .modelCnName("大疆机场M30")
                            .dockSn("")
                            .modifyTime(startTime)
                            .build());
                }
            }
        }
        return ServiceRo.resultSuccess(JSONObject.of("rows", objects));
    }

    /**
     * 获取航线信息
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> flightLines(JSONObject params) {
        final String sn = params.getString("sn");
        final String companyCode = params.getString("companyCode");
        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode);


        final JSONObject hangarListGet = httpRequest.hangarListGet(DataCacheService.tianyuLoginMap.get(ykCompanyId));
        final JSONArray hangarList = hangarListGet.getJSONArray("content");

        final Optional<Object> objectStream = hangarList.stream().filter(o -> {
            final JSONObject box0 = JSONObject.from(o);
            return sn.equals(box0.getString("boxSn"));
        }).findFirst();
        if (objectStream.isPresent()) {
            log.info("机场航线");
            final JSONObject object = JSONObject.from(objectStream.get());
            final String dockSn = object.getString("hangarId");
            final JSONObject lastLineGet = httpRequest.lastLineGet(DataCacheService.tianyuLoginMap.get(ykCompanyId), dockSn);
            log.info(lastLineGet.toJSONString());
            final Integer state = lastLineGet.getInteger("state");
            if (state != 0) {
                return ServiceRo.resultFailed("平台错误").setCode(state);
            }
            final JSONObject lastLine = lastLineGet.getJSONObject("content");
            return ServiceRo.resultSuccess(lastLine);
        } else {
            log.info("无人机航线");
            final JSONObject lastLineGet = httpRequest.lastLineGet(DataCacheService.tianyuLoginMap.get(ykCompanyId), sn);
            log.error(lastLineGet.toJSONString());
            final Integer state = lastLineGet.getInteger("state");
            if (state != 0) {
                return ServiceRo.resultFailed("平台错误").setCode(state);
            }
            final JSONObject lastLine = lastLineGet.getJSONObject("content");
            return ServiceRo.resultSuccess(lastLine);
        }
    }

    /**
     * 加载机库摄像头直播画面/推流
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> dockCameraLive(JSONObject params) {
        // 机库设备编号
        final String sn = params.getString("sn");
        final String companyCode0 = params.getString("companyCode");

        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode0);
        final JSONObject outVideo = httpRequest.hangarOutVideoGet(DataCacheService.tianyuLoginMap.get(ykCompanyId), sn, "flv");
        final JSONObject inVideo = httpRequest.hangarInVideoGet(DataCacheService.tianyuLoginMap.get(ykCompanyId), sn, "flv");
        log.info(outVideo.toJSONString());
        log.info(inVideo.toJSONString());
        final String outVideoString = outVideo.getString("content");
        final String inVideoString = inVideo.getString("content");
        return ServiceRo.resultSuccess(JSONObject.of(
                "sn", sn,
                "flvUrl", outVideoString == null ? "" : outVideoString,
                "flvUrl-in", inVideoString == null ? "" : inVideoString
        ));
    }

    /**
     * 加载飞行器摄像头直播画面/推流
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> aircraftCameraLive(JSONObject params) {
        // 设备编号（无人机设备编号）
        final String sn = params.getString("sn");
        return ServiceRo.resultSuccess(JSONObject.of(
                "sn", sn,
                "flvUrl", "http://hangar-video.yukong.live:8080/webrtc/M26220230415013.flv"
        ));
//        final String companyCode0 = params.getString("companyCode");
//
//        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode0);
//        final JSONObject boxVideo = httpRequest.boxLivePullGetPrefix(DataCacheService.tianyuLoginMap.get(ykCompanyId), sn);
//        System.out.println(boxVideo);
//        if (boxVideo.getInteger("state") != 0) {
//            log.error(boxVideo.toJSONString());
//            return ServiceRo.resultSuccess(JSONObject.of(
//                    "sn", sn,
//                    "flvUrl", ""
//            ));
//        }
//        final JSONObject content = boxVideo.getJSONObject("content");
//        return ServiceRo.resultSuccess(JSONObject.of(
//                "sn", sn,
//                "flvUrl", content == null ? "" : content.getString("flv")
//        ));
    }

    /**
     * 一键起飞
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> takeoffToPoint(JSONObject params) {
        // 设备编号（无人机设备编号）
        final String sn = params.getString("sn");
        final String companyCode = params.getString("companyCode");
        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode);
        final JSONObject hangarListGet = httpRequest.hangarListGet(DataCacheService.tianyuLoginMap.get(ykCompanyId));
        final JSONArray hangarList = hangarListGet.getJSONArray("content");

        final Optional<Object> objectStream = hangarList.stream().filter(o -> {
            final JSONObject box0 = JSONObject.from(o);
            return sn.equals(box0.getString("boxSn"));
        }).findFirst();
        if (objectStream.isPresent()) {
            log.info("机场一键起飞");
            final JSONObject object = JSONObject.from(objectStream.get());
            final String dockSn = object.getString("hangarId");
            final Double hangarLng = object.getDouble("hangarLng");
            final Double hangarLat = object.getDouble("hangarLat");
            final JSONObject dockOsd = DataCacheService.dockOsdMap.get(dockSn);
            final Double targetHeight = dockOsd.getDouble("hangarAltitude");
            if (hangarLng == null || hangarLat == null) {
                return ServiceRo.resultFailed("机场经纬度实时获取失败");
            }
            if (targetHeight == null) {
                return ServiceRo.resultFailed("获取不到机场海拔高度");
            }
            final JSONObject params01 = JSONObject.of();
            params01.put("targetLatitude", hangarLat);
            params01.put("targetLongitude", hangarLng);
            params01.put("targetHeight", targetHeight + 50);
            params01.put("securityTakeoffHeight", 50);
            params01.put("rthAltitude", 50);
            params01.put("maxSpeed", 12);
            params01.put("rcLostAction", 2);
            params01.put("rthMode", 1);
            params01.put("exitWaylineWhenRcLost", 1);
            params01.put("commanderModeLostAction", 1);
            params01.put("commanderFlightMode", 1);
            params01.put("commanderFlightHeight", 50);
            log.info(params01.toJSONString());
            final JSONObject result = httpRequest.hangarUavTakeoffPost(DataCacheService.tianyuLoginMap.get(ykCompanyId),
                    JSONObject.of("hangarId", dockSn, "command", 10016, "params", params01)
            );
            final Integer state = result.getInteger("state");
            log.info(result.toJSONString());
            if (state != 0) {
                return ServiceRo.resultFailed(String.valueOf(state));
            }
            return ServiceRo.resultSuccess();
        } else {
            log.info("无人机一键起飞");
            final JSONObject paramsContent = new JSONObject();
//            commandSendService.publishCommand(
//                    ykCompanyId,
//                    sn,
//                    CommandSendService.UavCommand.COMMAND_1002.getCode(),
//                    paramsContent);
            return ServiceRo.resultSuccess();
        }
    }

    /**
     * 指点飞行
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> flyToPoint(JSONObject params) {
        // 设备编号（无人机设备编号）
        final String sn = params.getString("sn");
        final JSONArray points = params.getJSONArray("points");
        if (points.size() == 0) {
            return ServiceRo.resultFailed("航点参数异常");
        }
        final FlyToPointDTO.Point point1 = JSON.to(FlyToPointDTO.Point.class, points.get(0));
        final String companyCode = params.getString("companyCode");
        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode);
        final JSONObject paramsContent = new JSONObject();
        paramsContent.put("longitude", point1.getLongitude());
        paramsContent.put("latitude", point1.getLatitude());
        paramsContent.put("height", point1.getHeight());
        paramsContent.put("speed", 5);
        paramsContent.put("mode", 1);
        commandSendService.publishCommand(
                ykCompanyId,
                sn,
                CommandSendService.UavCommand.COMMAND_1015.getCode(),
                paramsContent);
        DataCacheService.currentProcessCommandMap.put(sn, CurrentProcessCommand.builder()
                .command("FLY_TO_POINT")
                .params(params)
                .build());
        return ServiceRo.resultSuccess();
    }

    /**
     * 任务飞行
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> flyTask(JSONObject params) {
        // 设备编号（无人机设备编号）
        final String sn = params.getString("sn");
        //  40 否 航线任务ID（不指定时,默认使用上一个航线任务  ID或唯一的航线任务ID）
        String missionId = params.getString("missionId");
        final String companyCode = params.getString("companyCode");
        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode);
        final JSONObject hangarListGet = httpRequest.hangarListGet(DataCacheService.tianyuLoginMap.get(ykCompanyId));
        final JSONArray hangarList = hangarListGet.getJSONArray("content");

        final Optional<Object> objectStream = hangarList.stream().filter(o -> {
            final JSONObject box0 = JSONObject.from(o);
            return sn.equals(box0.getString("boxSn"));
        }).findFirst();
        if (objectStream.isPresent()) {
            log.info("机场任务飞行");
            final JSONObject object = JSONObject.from(objectStream.get());
            final String dockSn = object.getString("hangarId");
            if (missionId == null) {
                final JSONObject lastLineGet = httpRequest.lastLineGet(DataCacheService.tianyuLoginMap.get(ykCompanyId), dockSn);
                log.info(lastLineGet.toJSONString());
                final JSONObject content = lastLineGet.getJSONObject("content");
                final JSONArray messions = content.getJSONArray("messions");
                if (messions.size() > 0) {
                    final JSONObject line1 = JSONObject.from(messions.get(0));
                    missionId = line1.getString("missionId");
                }
            }
            final JSONObject result = httpRequest.hangarLineExecutePost(DataCacheService.tianyuLoginMap.get(ykCompanyId),
                    JSONObject.of("deviceSn", dockSn, "templateId", missionId)
            );

            DataCacheService.currentProcessCommandMap.put(sn, CurrentProcessCommand.builder()
                    .command("FLIGHT_TASK")
                    .params(params)
                    .build());
            log.info(result.toJSONString());
            return ServiceRo.resultSuccess();
        } else {
            log.info("无人机任务飞行");
            final JSONObject paramsContent = new JSONObject();
            commandSendService.publishCommand(
                    ykCompanyId,
                    sn,
                    CommandSendService.UavCommand.COMMAND_1002.getCode(),
                    paramsContent);
            return ServiceRo.resultSuccess();
        }
    }

    /**
     * 一键悬停
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> flyPause(JSONObject params) {
        // 设备编号（无人机设备编号）
        final String sn = params.getString("sn");
        final String companyCode = params.getString("companyCode");
        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode);
        final JSONObject hangarListGet = httpRequest.hangarListGet(DataCacheService.tianyuLoginMap.get(ykCompanyId));
        final JSONArray hangarList = hangarListGet.getJSONArray("content");
        final Optional<Object> objectStream = hangarList.stream().filter(o -> {
            final JSONObject box0 = JSONObject.from(o);
            return sn.equals(box0.getString("boxSn"));
        }).findFirst();
        if (objectStream.isPresent()) {
            log.info("机场控制悬停");
            final TianyuPB.TelemetryData boxOsd = DataCacheService.boxOsdMap.get(sn);
            final TianyuPB.UavState boxStatus = DataCacheService.boxStatusMap.get(sn);
            final int flightMode = boxOsd.getFlightMode();
            switch (flightMode) {
                // 航线中暂停航线
                case 14 -> {
                    final JSONObject object = JSONObject.from(objectStream.get());
                    final String dockSn = object.getString("hangarId");
                    final JSONObject lineControl = httpRequest.lineControl(DataCacheService.tianyuLoginMap.get(ykCompanyId), dockSn, 1);
                    log.error(lineControl.toJSONString());
                    final Integer state = lineControl.getInteger("state");
                    if (state != 0) {
                        return ServiceRo.resultFailed("平台错误").setCode(state);
                    }
                    return ServiceRo.resultSuccess();
                }
                // 返航中暂停返航
                case 15 -> {
                    commandSendService.publishCommand(
                            ykCompanyId,
                            sn,
                            CommandSendService.UavCommand.COMMAND_1008.getCode(),
                            null);
                    return ServiceRo.resultSuccess();
                }
            }
            // 指点飞行 取消指点飞行
            if (boxStatus.getMissionState().getIsPointControl() == 1) {
                commandSendService.publishCommand(
                        ykCompanyId,
                        sn,
                        CommandSendService.UavCommand.COMMAND_1016.getCode(),
                        null);
                return ServiceRo.resultSuccess();
            }
            return ServiceRo.resultSuccess();
        } else {
            log.info("无人机暂停飞行");
//            final JSONObject paramsContent = new JSONObject();
//            commandSendService.publishCommand(
//                    ykCompanyId,
//                    sn,
//                    CommandSendService.UavCommand.COMMAND_1002.getCode(),
//                    paramsContent);
            return ServiceRo.resultSuccess();
        }


    }

    /**
     * 继续飞行
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> flyRecovery(JSONObject params) {
        // 设备编号（无人机设备编号）
        final String sn = params.getString("sn");
        final String companyCode = params.getString("companyCode");
        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode);
        final JSONObject hangarListGet = httpRequest.hangarListGet(DataCacheService.tianyuLoginMap.get(ykCompanyId));
        final JSONArray hangarList = hangarListGet.getJSONArray("content");

        final Optional<Object> objectStream = hangarList.stream().filter(o -> {
            final JSONObject box0 = JSONObject.from(o);
            return sn.equals(box0.getString("boxSn"));
        }).findFirst();
        if (objectStream.isPresent()) {
            log.info("机场继续飞行");
            final CurrentProcessCommand currentProcessCommand = DataCacheService.currentProcessCommandMap.get(sn);
            if (currentProcessCommand == null) {
                return ServiceRo.resultFailed("未记录到上个指令动作, 无法恢复");
            }
            final String method = currentProcessCommand.getCommand();
            final ThirdMethodEnum methodEnum = ThirdMethodEnum.findByMethod(method);
            switch (methodEnum) {
                case FLIGHT_TASK -> {
                    final JSONObject object = JSONObject.from(objectStream.get());
                    final String dockSn = object.getString("hangarId");
                    final JSONObject lineControl = httpRequest.lineControl(DataCacheService.tianyuLoginMap.get(ykCompanyId), dockSn, 2);
                    log.error(lineControl.toJSONString());
                    final Integer state = lineControl.getInteger("state");
                    if (state != 0) {
                        return ServiceRo.resultFailed("平台错误").setCode(state);
                    }
                    return ServiceRo.resultSuccess();
                }
                case FLY_TO_POINT -> {
                    return flyToPoint(currentProcessCommand.getParams());
                }
                case RETURN_HOME -> {
                    commandSendService.publishCommand(
                            ykCompanyId,
                            sn,
                            CommandSendService.UavCommand.COMMAND_1007.getCode(),
                            null);
                    return ServiceRo.resultSuccess();
                }
            }
            return ServiceRo.resultSuccess();
        } else {
            log.info("无人机继续航线飞行");
            return ServiceRo.resultSuccess();
        }
    }

    /**
     * 一键返航
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> returnHome(JSONObject params) {
        // 设备编号（无人机设备编号）
        final String sn = params.getString("sn");
        final String companyCode = params.getString("companyCode");
        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode);
        final JSONObject paramsContent = new JSONObject();
        commandSendService.publishCommand(
                ykCompanyId,
                sn,
                CommandSendService.UavCommand.COMMAND_1007.getCode(),
                paramsContent);
        DataCacheService.currentProcessCommandMap.put(sn, CurrentProcessCommand.builder()
                .command("RETURN_HOME")
                .params(params)
                .build());
        return ServiceRo.resultSuccess();
    }

    /**
     * 云台镜头重置
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> gimbalReset(JSONObject params) {
        // 设备编号（无人机设备编号）
        final String sn = params.getString("sn");
        // 镜头模式 RECENTER=回中 DOWN=正射
        final String mode = params.getString("mode");

        final String companyCode = params.getString("companyCode");
        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode);
        final JSONObject paramsContent = new JSONObject();
        if (Objects.equals(mode, "RECENTER")) {
            commandSendService.publishCommand(
                    ykCompanyId,
                    sn,
                    CommandSendService.UavCameraCommand.COMMAND_1109.getCode(),
                    paramsContent);
        } else if (Objects.equals(mode, "DOWN")) {
            paramsContent.put("ptzPitch", -90);
            paramsContent.put("ptzRoll", 0);
            paramsContent.put("ptzYaw", 0);
            commandSendService.publishCommand(
                    ykCompanyId,
                    sn,
                    CommandSendService.UavCameraCommand.COMMAND_1129.getCode(),
                    paramsContent);
        }

        return ServiceRo.resultSuccess();
    }

    /**
     * 云台变焦
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> cameraFocalLengthSet(JSONObject params) {
        // 设备编号（无人机设备编号）
        final String sn = params.getString("sn");
        // 变焦倍数：1~100
        final Double zoomFactor = params.getDouble("zoomFactor");
        final String companyCode = params.getString("companyCode");
        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode);
        final JSONObject paramsContent = new JSONObject();
        double zoomFactor0;
        if (zoomFactor > 200) {
            zoomFactor0 = 200;
        } else if (zoomFactor < 0) {
            zoomFactor0 = 0;
        } else {
            zoomFactor0 = zoomFactor;
        }
        paramsContent.put("zoomAbs", zoomFactor0);
        commandSendService.publishCommand(
                ykCompanyId,
                sn,
                CommandSendService.UavCameraCommand.COMMAND_1126.getCode(),
                paramsContent);
        return ServiceRo.resultSuccess();
    }

    /**
     * 云台镜头切换
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> liveLensChange(JSONObject params) {
        // 设备编号（无人机设备编号）
        final String sn = params.getString("sn");
        // 镜头类型 NORMAL=默认 WIDE=广角 ZOOM=变焦 IR=红外
        final String mode = params.getString("mode");

        final String companyCode = params.getString("companyCode");
        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode);
        final JSONObject paramsContent = new JSONObject();
        if (Objects.equals(mode, "NORMAL") || Objects.equals(mode, "WIDE")) {
            paramsContent.put("cameraSource", 0);
        } else if (Objects.equals(mode, "ZOOM")) {
            paramsContent.put("cameraSource", 1);
        } else if (Objects.equals(mode, "IR")) {
            paramsContent.put("cameraSource", 2);
        }
        commandSendService.publishCommand(
                ykCompanyId,
                sn,
                CommandSendService.UavCameraCommand.COMMAND_1116.getCode(),
                paramsContent);
        return ServiceRo.resultSuccess();
    }

    /**
     * 云台镜头清晰度切换
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> liveSetQuality(JSONObject params) {
        // 设备编号（无人机设备编号）
        final String sn = params.getString("sn");
        // 镜头清晰度
        // AUTO=自适应
        // FLUENT=流畅 1280 * 720、1Mbps
        // SD=标清 1280 * 720、1Mbps
        // HD=高清 1920 * 1080、3Mbps
        // FHD=超清 1920 *
        final String mode = params.getString("mode");

        final String companyCode = params.getString("companyCode");
        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode);
        final JSONObject paramsContent = new JSONObject();


        switch (mode) {
            case "FLUENT", "SD" -> {
                paramsContent.put("xPixel", 1280);
                paramsContent.put("yPixel", 720);
            }
            default -> {
                paramsContent.put("xPixel", 1920);
                paramsContent.put("yPixel", 1080);
            }
        }
        commandSendService.publishCommand(
                ykCompanyId,
                sn,
                CommandSendService.UavCameraCommand.COMMAND_1121.getCode(),
                paramsContent);
        return ServiceRo.resultSuccess();
    }

    /**
     * 云台视觉中心点切换
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> cameraAim(JSONObject params) {
        // 设备编号（无人机设备编号）
        final String sn = params.getString("sn");
        // 目标坐标 x（最小值：0,最大值:1） 以镜头的左上角为坐标中心点，水平方向为 x
        final Double x = params.getDouble("x");
        // 目标坐标 y（最小值：0,最大值:1） 以镜头的左上角为坐标中心点，竖直方向为 y
        final Double y = params.getDouble("y");


        final String companyCode = params.getString("companyCode");
        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode);
        final JSONObject paramsContent = new JSONObject();

        paramsContent.put("focalX", x);
        paramsContent.put("focalY", y);
        commandSendService.publishCommand(
                ykCompanyId,
                sn,
                CommandSendService.UavCameraCommand.COMMAND_1124.getCode(),
                paramsContent);


        return ServiceRo.resultSuccess();
    }

    /**
     * 手控摇杆操作
     *
     * @param params
     * @return 执行结果
     */
    @Override
    public ServiceRo<?> droneControl(JSONObject params) {
        final ServiceRo<?> serviceRo = flyPause(params);
        log.info("droneControl-flyPause: {}", serviceRo.toString());
        // 设备编号（无人机设备编号）
        final String sn = params.getString("sn");
        // 摇杆行为
        // W=前进
        // S=后退
        // A=左平移
        // D=右平移
        // Q=左转
        // E=右转
        // R=升高
        // F=降高
        final String mode = params.getString("mode");
        // 移动速度：米每秒 m/s
        final Double speed = params.getDouble("speed");

        final String companyCode = params.getString("companyCode");
        final Integer ykCompanyId = DataCacheService.THIRD_ID_TO_TY_ID_MAP.get(companyCode);
        final JSONObject paramsContent = new JSONObject();
        paramsContent.put("fbSpeed", 0);
        paramsContent.put("lrSpeed", 0);
        paramsContent.put("udSpeed", 0);
        paramsContent.put("yawAngle", 0);
        switch (mode) {
            case "W" -> paramsContent.put("fbSpeed", speed);
            case "S" -> paramsContent.put("fbSpeed", -speed);
            case "A" -> paramsContent.put("lrSpeed", -speed);
            case "D" -> paramsContent.put("lrSpeed", speed);
            case "Q" -> paramsContent.put("yawAngle", -speed);
            case "E" -> paramsContent.put("yawAngle", speed);
            case "R" -> paramsContent.put("udSpeed", speed);
            case "F" -> paramsContent.put("udSpeed", -speed);
        }
        paramsContent.put("executionTime", 100);
        commandSendService.publishCommand(
                ykCompanyId,
                sn,
                CommandSendService.UavCommand.COMMAND_1001.getCode(),
                paramsContent);

        return ServiceRo.resultSuccess();
    }
}
